package com.weiaibenpao.demo.chislim.ui.fragment;

import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.PolylineOptions;
import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.TwoPointLine;
import com.weiaibenpao.demo.chislim.bean.Points;
import com.weiaibenpao.demo.chislim.db.preferences.LocationPreferences;
import com.weiaibenpao.demo.chislim.ui.activity.running.SearchLocationActivity;
import com.weiaibenpao.demo.chislim.ui.activity.running.SetDistanceActivity;
import com.weiaibenpao.demo.chislim.ui.activity.running.StartRunActivity;
import com.weiaibenpao.demo.chislim.ui.widget.PaletteView;
import com.weiaibenpao.demo.chislim.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class InterestRunFragment extends Fragment {

    @BindView(R.id.map_view)
    MapView mapView;
    @BindView(R.id.text_set_distance)
    TextView textSetDistance;
    Unbinder unbinder;
    @BindView(R.id.paint_view)
    PaletteView paintView;
    private AMap map;
    private View mView;
    private String latitude;
    private String longitude;
    private float runDistance;//设定跑步的距离
    private LatLng latLng;//起始点经纬度
    private LatLng centerLatLng;//终点经纬度坐标
    private int width;
    private int height;
    public boolean isFirstDown=true;

    private List<Float> xList;
    private List<Float> yList;
    private List<Points> screenList = new ArrayList<>();
    public static List<PolylineOptions> optionsList;
    public static List<TwoPointLine> twoPointLineList;
    public static StringBuilder mInterestPoint = new StringBuilder();//趣味跑数据格式
    private float hand_x = 0;
    private float hand_y = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    Logger.e("i=="+mInterestPoint.toString());

                    Bitmap bitmap = paintView.buildBitmap();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                    byte[] bytes = baos.toByteArray();
                    StartRunActivity.openActivity(getContext(), 5, "", runDistance,"", 0, bytes, centerLatLng.latitude, centerLatLng.longitude);
                    break;
            }
        }
    };
    private PolylineOptions polygonOptions;
    public static int totalNum;

    public InterestRunFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (mView != null) {
            if (mView.getParent() != null) {
                ((ViewGroup) mView.getParent()).removeView(mView);
            }
        }
        mView = inflater.inflate(R.layout.fragment_interest_run, container, false);
        unbinder = ButterKnife.bind(this, mView);
        EventBus.getDefault().register(this);
        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mapView.onCreate(savedInstanceState);
        width = paintView.getWidth();//画布中心点x坐标
        height = paintView.getHeight();//画布中心点y坐标

        paintView.setOnActionListener(new PaletteView.OnMoveListener() {
            /**
             * 手指第一次按下去作为起始点
             */
            @Override
            public void onDownListener(float x, float y) {
                xList = new ArrayList<>();
                yList = new ArrayList<>();
                hand_x = x;
                hand_y = y;
                xList.add(x);
                yList.add(y);
               if (isFirstDown){
                   isFirstDown=false;
                   getMapCenterPoint(hand_x,hand_y);
               }
            }

            @Override
            public void onMoveListener(float x, float y) {

                xList.add(x);
                yList.add(y);
            }

            @Override
            public void onUpListener() {
                Points points = new Points(xList, yList);
                screenList.add(points);
            }
        });

        paintView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                paintView.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });

        initMap();
    }

    private void initMap() {
        if (map == null) {
            map = mapView.getMap();
        } else {
            map.clear();
            map = mapView.getMap();
        }
        map.getUiSettings().setZoomControlsEnabled(false);
        latitude = LocationPreferences.getInstance().getLocationLatitude();
        longitude = LocationPreferences.getInstance().getLocationLongitude();
        latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
        centerLatLng=new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
        setIntro(centerLatLng);
//        }

    }

    @OnClick({R.id.text_clear, R.id.text_search, R.id.btn_start_run, R.id.layout_set_distance})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_clear:
                clearPoint();
                break;
            case R.id.text_search:
                SearchLocationActivity.openActivity(getContext());
                break;
            case R.id.btn_start_run:
                startRun();
                break;
            case R.id.layout_set_distance:
                SetDistanceActivity.openActivity(getContext());
                break;
        }
    }

    /**
     * 清楚画图操作
     */
    private void clearPoint() {
        paintView.clear();
        hand_x = 0;
        hand_y = 0;
        isFirstDown=true;
//        if (xList != null && xList.size() > 0) {
//
//            xList.clear();
//        }
//        if (yList != null && yList.size() > 0) {
//            yList.clear();
//        }
        if (screenList != null && screenList.size() > 0) {
            screenList.clear();
        }
    }

    /**
     * 开始跑步的逻辑
     */
    private void startRun() {


        if (runDistance <= 0) {
            Toast.makeText(getContext(), "请输入跑步距离", Toast.LENGTH_SHORT).show();
            return;
        }
        if (screenList != null && screenList.size() <= 0) {
            Toast.makeText(getContext(), "请在地图上绘制出想跑的图形", Toast.LENGTH_SHORT).show();
            return;
        }

        getPointToLatLng();
    }

    private void getPointToLatLng() {
        optionsList=new ArrayList<>();
        twoPointLineList = new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < screenList.size(); i++) {
                    int num =  screenList.get(i).getX().size();
                    totalNum+=num;

                    polygonOptions = new PolylineOptions();
                    polygonOptions.width(15).color(getResources().getColor(R.color.color_un_run)).zIndex(200).visible(true);
                    for (int j = 0; j < num; j++) {
                        if(j < num-1){ //added by ZJL 所有笔画均可视为由n个最短的两点线段组成，记录这些最短的两点线段
                            LatLng start = getLatLong(new Point(Math.round( screenList.get(i).getX().get(j)), Math.round(screenList.get(i).getY().get(j))));
                            LatLng end = getLatLong(new Point(Math.round( screenList.get(i).getX().get(j+1)), Math.round(screenList.get(i).getY().get(j+1))));
                            TwoPointLine twoPointPolyline;
                            if(j == 0){
                                twoPointPolyline = new TwoPointLine(true);
                            }else {
                                twoPointPolyline = new TwoPointLine(false);
                            }
                            twoPointPolyline.getLatLngs().add(start);
                            twoPointPolyline.getLatLngs().add(end);
                            twoPointLineList.add(twoPointPolyline);

                            if (j==(num-1-1)){//最后一条线段
                                mInterestPoint.append(start.longitude).append(",").append(start.latitude).append(":");
                                mInterestPoint.append(end.longitude).append(",").append(end.latitude).append(";");}
                            else {
                                mInterestPoint.append(start.longitude).append(",").append(start.latitude).append(":");
                            }
                        }
                        polygonOptions.add(getLatLong(new Point(Math.round( screenList.get(i).getX().get(j)), Math.round(screenList.get(i).getY().get(j)))));
                    }
                    optionsList.add(polygonOptions);
                }
                mHandler.sendEmptyMessage(100);

            }
        }).start();
//        LocationPreferences.getInstance().

    }

    @Subscribe
    public void onEvent(LatLng latLng) {
        this.latLng = latLng;
        if (hand_y == 0 && hand_x == 0) {
            centerLatLng=latLng;
            setIntro(latLng);
        } else {
            getMapCenterPoint(hand_x, hand_y);
        }

//        LocationPreferences.getInstance().setLocationLatitude(String.valueOf(latLng.latitude));
//        LocationPreferences.getInstance().setLocationLongitude(String.valueOf(latLng.longitude));

    }

    /**
     * @param x 触点起点x轴
     * @param y 触点起点y轴
     */
    public void getMapCenterPoint(float x, float y) {

        //将当前经纬度坐标转化为屏幕坐标
        Point point = getScreen(latLng);
        float x1 = x - point.x;
        float y1 = y - point.y;
        //中心点经纬度转换成屏幕坐标
        Point centerPoint = getScreen(centerLatLng);
        Logger.e("before=="+centerLatLng.latitude+"   before=="+centerLatLng.longitude);

        //计算当前触点相对于中心点的位置

//        float x1 = (float) (x - width / 2.0);
//        float y1 = (float) (y - height / 2.0);
//        //计算屏幕中心点所在的位置
        int x2 = (int) (centerPoint.x- x1);
        int y2 = (int) (centerPoint.y -y1);
        //将接下来屏幕中点所在屏幕位置转化为实际地球经纬度
        centerLatLng = getLatLong(new Point(x2, y2));
       Logger.e("getMapCenterPoint=="+centerLatLng.latitude+"   getMapCenterPoint=="+centerLatLng.longitude);
        //设置地图中心点
        setIntro(centerLatLng);
    }

    /**
     * 切换地图显示中心点
     */
    public void setIntro(LatLng latLng) {
        //设置中心点和缩放比例
        map.moveCamera(CameraUpdateFactory.zoomTo(15f));
        map.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
    }

    /**
     * 根据屏幕坐标值返回地球经纬度值
     */
    public LatLng getLatLong(Point point) {
        return map.getProjection().fromScreenLocation(point);
    }

    /**
     * 根据地球经纬度值返回屏幕坐标值
     */
    public Point getScreen(LatLng latLng) {
        return map.getProjection().toScreenLocation(latLng);
    }

    @Override
    public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
        super.onMultiWindowModeChanged(isInMultiWindowMode);
        width = paintView.getWidth();
        height = paintView.getHeight();
    }

    @Subscribe
    public void onEvent(String distance) {
        runDistance = Float.parseFloat(distance);
        textSetDistance.setText(Utils.decimalFormat(runDistance) + "公里");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
        if (unbinder != null) unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);

    }


}
